package cn.finedo.highway.quartz;

import cn.finedo.common.date.DateUtil;
import cn.finedo.common.domain.CommonDataDomain;
import cn.finedo.common.domain.ReturnValueDomain;
import cn.finedo.fsdp.service.common.jdbc.JdbcTemplate;
import cn.finedo.highway.domain.ColumnDomain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @description:定时新增高速联网大屏数据
 * @author: lizheng
 * @createDate: 2023-2-19
 * @version: 1.0
 */
@Component
public class DataInitQuartz {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource(name = "fsdpJdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    /**
     * 每日0点30分定时执行数据汇总表数据初始化任务
     * @throws Exception
     */
    @Scheduled(cron = "30 00 00 * * ?")
//    @PostConstruct
    public void dataInitTask(){
        logger.info("定时执行数据汇总表数据初始化，开始....");
        ReturnValueDomain<Object> ret = dataInit();
        logger.info(ret.getResultdesc());
        logger.info("定时执行数据汇总表数据初始化，结束....");
    }

    public ReturnValueDomain<Object> dataInit(){
        ReturnValueDomain<Object> ret = new ReturnValueDomain<>();
        String initDate = DateUtil.getNowTime("yyyy-MM-dd");
        String updateDateSql = " update LW_DATASTATSQLATTR SET VALUESCRIPT = '"+ initDate +"' where COLUMNNAME = 'DATE_TIME' ";
        try {
            jdbcTemplate.updateNohis(updateDateSql);
        }catch (Exception e){
            logger.error("修改基础数据汇总表日期"+e.toString());
            return ret.setFail("修改基础数据汇总表日期"+e.toString());
        }

        String sql = "\t select a.dsid,a.TABLENAME,b.COLUMNNAME,b.VALUESCRIPT\n" +
                "\t\t\tfrom LW_DATASTATSQL a  \n" +
                "\t\t LEFT JOIN LW_DATASTATSQLATTR b on a.DSID = b.DSID\n" +
                "      where b.ISPRKEY = '是'";
        List<CommonDataDomain> tableDataList = new ArrayList<>();
        try {
            tableDataList = jdbcTemplate.query(sql);
        }catch (Exception e){
            logger.error("查询数据汇总表数据失败"+e.toString());
            return ret.setFail("查询数据汇总表数据失败"+e);
        }

        Map<String,List<ColumnDomain>> map = new HashMap<>();
        for(CommonDataDomain tableData:tableDataList){
            String dsid = tableData.getString("DSID");
            if(!map.containsKey(dsid)){
                List<ColumnDomain> dataDomainList = new ArrayList<>();
                map.put(dsid,dataDomainList);
            }
            List<ColumnDomain> dataList = map.get(dsid);
            ColumnDomain column = new ColumnDomain();
            column.setTablename(tableData.getString("TABLENAME"));
            column.setColumnname(tableData.getString("COLUMNNAME"));
            column.setValuescript(tableData.getString("VALUESCRIPT"));
            dataList.add(column);
        }

        Set<Map.Entry<String, List<ColumnDomain>>> entry = map.entrySet();
        for(Map.Entry<String, List<ColumnDomain>> columnData :entry){
            StringBuffer tableSql = new StringBuffer();
            List<ColumnDomain> sqlList = columnData.getValue();
            if(null != sqlList && sqlList.size()>0){
                String tableName = sqlList.get(0).getTablename();
                tableSql.append(" INSERT INTO ").append(tableName);
                StringBuffer columnSql = new StringBuffer();
                StringBuffer valueSql = new StringBuffer();
                columnSql.append(" ( ");
                valueSql.append(" VALUES( ");
                for(int i = 0;i<sqlList.size();i++){
                    columnSql.append(sqlList.get(i).getColumnname());
                    if(i != sqlList.size()-1){
                        columnSql.append(",");
                    }else{
                        columnSql.append(" ) ");
                    }
                    valueSql.append(" ' ").append(sqlList.get(i).getValuescript());
                    if(i != sqlList.size()-1){
                        valueSql.append(" ',");
                    }else{
                        valueSql.append(" ' ) ");
                    }
                }
                tableSql.append(columnSql).append(valueSql);
//                System.out.println("------------------------------------------");
//                System.out.println(columnSql);
//                System.out.println(valueSql);
//                System.out.println(tableSql);
//                System.out.println("------------------------------------------");
                try{
                    jdbcTemplate.updateNohis(tableSql.toString());
                }catch (Exception e){
                    logger.error(tableName+"数据初始化失败"+e.toString());
                    return ret.setFail(tableName+"数据初始化失败"+e);
                }
            }
        }
        return ret.setSuccess(initDate+"数据初始化成功");
    }
}
